package com.general.framework.cc.thread;

public class GetBankMoney {
    public static void main(String[] args) {
        Account account = new Account("my Account", 100);
        Bank me = new Bank(account, 50);
        Bank my = new Bank(account, 100);
        new Thread(me,"我自己").start();
        new Thread(my,"我对象").start();
    }
}
class Account{
    // 账户
    public String name;
    // 余额
    public int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}
class Bank implements Runnable{
    Account account; // 账号
    int needMoney; // 取多少钱

    public Bank(Account account, int needMoney) {
        this.account = account;
        this.needMoney = needMoney;
    }
    // 线程不安全的做法
    @Override
    public void run() {
        if (account.money - needMoney < 0) {
            System.out.println("余额不足");
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        account.money = account.money - needMoney;
        System.out.println(Thread.currentThread().getName() + "取出" + needMoney);
        System.out.println(account.name + "余额:" + account.money);
    }
    /*
    线程安全的做法
    @Override
    public void run() {
        synchronized (account){
            if (account.money - needMoney < 0) {
                System.out.println("余额不足");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money = account.money - needMoney;
            System.out.println(Thread.currentThread().getName() + "取出" + needMoney);
            System.out.println(account.name + "余额:" + account.money);
        }
    }
    */
}
/*
我自己取出50
我对象取出100
my Account余额:-50
my Account余额:-50

Process finished with exit code 0
*/
